package yogaService

import (
	"duoke/model"
	"duoke/model/yogaModel"
	"duoke/service"
	"duoke/service/common"
	utils "duoke/utils/common"
	"duoke/utils/gconv"
	"duoke/utils/gjson"
	"duoke/utils/orm"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/gogf/gf/v2/os/gtime"
	"strings"
)

var SchoolTimetable = new(schoolTimetableService)

type schoolTimetableService struct{}

func (s *schoolTimetableService) Save(c *gin.Context, req *yogaModel.ReqSchoolTimetable) error {
	const (
		TableSchoolTimetable = "yoga_school_timetable"
		TableGroupClass      = "yoga_group_class"
		TableTeacher         = "yoga_teacher"
	)

	// 获取今日时间
	account, err := service.Request.Account(c)
	if err != nil {
		return errors.New("账户信息获取失败")
	}
	if req.ReservationWeek > 7 || req.ReservationWeek < 1 {
		return errors.New("【ReservationWeek】取值范围1-7")
	}
	format := gtime.Now().Format("Ym")
	if req.ReservationDate < gconv.Int(format) {
		return errors.New("选择时间不能小于今天")
	}
	req.Acid = account.Id

	if req.ReservationMorning != nil {
		req.ReservationMorning = gjson.StructOrMap2Json(req.ReservationMorning)
	}
	if req.ReservationAfternoon != nil {
		req.ReservationAfternoon = gjson.StructOrMap2Json(req.ReservationAfternoon)
	}
	var count int64
	// 查询是否存在数据
	if req.ClassType < 3 {
		res, err := orm.Db.Where("class_type=? and id=?", req.ClassType, req.ClassId).
			Table(TableGroupClass).Cols("name").Get(&req.ClassName)
		if !res || err != nil {
			return errors.New("课程不存在")
		}
	} else {
		res, err := orm.Db.Where("id=?", req.ClassId).
			Table(TableTeacher).Cols("name").Get(&req.ClassName)
		if !res || err != nil {
			return errors.New("教师不存在")
		}
	}

	// 查询当前日期有没有重复
	if req.Id > 0 {
		update, err := orm.Db.Where("id=?", req.Id).Table(TableSchoolTimetable).Update(req)
		if err != nil || update == 0 {
			return errors.New("更新失败")
		}
	} else {
		count, err = orm.Db.Where("reservation_week=? and class_type=? and class_id=?",
			req.ReservationWeek, req.ClassType, req.ClassId).Table(TableSchoolTimetable).Count()
		if count > 0 || err != nil {
			return errors.New("已经存在该日期")
		}
		req.State = 1
		insert, err := orm.Db.Table(TableSchoolTimetable).Insert(req)
		if err != nil || insert == 0 {
			return errors.New("添加失败")
		}
	}
	return nil
}
func (s *schoolTimetableService) List(req *yogaModel.ReqSchoolTimetable) (*[]yogaModel.ReqSchoolTimetable,
	error) {
	const TablesDate = "yoga_school_timetable"
	var m []yogaModel.ReqSchoolTimetable
	session := orm.Db.NewSession()
	if req.ClassType != 0 {
		session.Where("class_type=?", req.ClassType)
	}
	if req.ClassId != 0 {
		session.Where("class_id=?", req.ClassId)
	}
	err := session.Table(TablesDate).Find(&m)
	return &m, err
}

func (s *schoolTimetableService) GroupClass(req *yogaModel.SearchSchoolTimetable) (*model.RspList, error) {
	const (
		TableSchoolTimetable = "yoga_school_timetable"
	)

	// 如果星期没传 判断今天是周几
	weekday := gtime.Now().Weekday()
	tody := utils.Common.GetWeekDays(weekday)
	if req.Week == 0 {
		req.Week = tody
	}
	var yc []yogaModel.JoinDateToGroupClass
	// 查询今天的课程
	cols := orm.Db.Where("reservation_week=? and venue_id=? and a.class_type=? and reservation_date=? and state=1",
		req.Week, req.VenueId, req.ClassType, req.Year).
		Table(TableSchoolTimetable).Alias("a").Join("inner",
		"yoga_group_class b", "a.class_type=b.class_type and a.class_id=b.id").
		Cols("b.*,reservation_morning,reservation_afternoon")
	count, err := common.Tales.PageList(cols, req.PageNo, req.PageSize).
		OrderBy("weight desc").FindAndCount(&yc)
	if err != nil {
		return nil, err
	}
	for k, class := range yc {
		var yt [2]yogaModel.TimeSlot
		if class.ReservationMorning != nil {
			json := gjson.StructOrMap2Json(class.ReservationMorning)
			gjson.Json2StructOrMap(json, &yt[0])
		}
		if class.ReservationAfternoon != nil {
			json := gjson.StructOrMap2Json(class.ReservationAfternoon)
			gjson.Json2StructOrMap(json, &yt[1])
		}
		yc[k].TimeStr = utils.Common.GetBelongingSlot(&yt)
	}
	if err != nil {
		return nil, err
	}
	currentTime := gtime.Now().Format("15:04") // 获取 HH:mm 格式的时间
	for k, item := range yc {
		if item.TimeStr != "" {
			split := strings.Split(item.TimeStr, "-")
			if utils.Common.IsInTimeSlot(currentTime, split[0], split[1]) == false || req.Week < tody {
				yc[k].IsReservation = 1
			}
		}
	}
	// 查询该用户有无购买
	return &model.RspList{
		List:  &yc,
		Total: count,
	}, err
}

func (s *schoolTimetableService) Teacher(req *yogaModel.SearchSchoolTimetable) (*model.RspList, error) {
	const TableSchoolTimetable = "yoga_school_timetable"
	var yc []yogaModel.JoinDate2Teacher
	cols := orm.Db.Where("reservation_week=? and venue_id=? and a.class_type=? and reservation_date=? and state=1",
		req.Week, req.VenueId, req.ClassType, req.Year).Table(TableSchoolTimetable).Alias("a").
		Join("inner", "yoga_teacher as b", "class_id=b.id").
		Cols("b.*,reservation_morning,reservation_afternoon,a.class_type")
	count, err := common.Tales.PageList(cols, req.PageNo, req.PageSize).
		OrderBy("weight desc").FindAndCount(&yc)
	if err != nil {
		return nil, err
	}
	for k, class := range yc {
		var yt [2]yogaModel.TimeSlot
		if class.ReservationMorning != nil {
			json := gjson.StructOrMap2Json(class.ReservationMorning)
			gjson.Json2StructOrMap(json, &yt[0])
		}
		if class.ReservationAfternoon != nil {
			json := gjson.StructOrMap2Json(class.ReservationAfternoon)
			gjson.Json2StructOrMap(json, &yt[1])
		}
		yc[k].TimeStr = utils.Common.GetBelongingSlot(&yt)
	}
	if err != nil {
		return nil, err
	}
	return &model.RspList{
		List:  &yc,
		Total: count,
	}, err
}
